﻿using System;
using System.Linq;

using MicroDb.Options;

using Microsoft.Extensions.Options;

namespace MicroDb.Generate
{
    class ConfigureOptions : IConfigureNamedOptions<MicroDbOptions>
    {
        private readonly string connectionStrings;

        private readonly string name;

        public ConfigureOptions(string connectionStrings, string name)
        {
            this.connectionStrings = connectionStrings;
            this.name = name;
        }

        public void Configure(string name, MicroDbOptions options)
        {
            Configure(options, name, connectionStrings);
        }

        public void Configure(MicroDbOptions options)
        {
            Configure(name, options);
        }

        public void Configure(MicroDbOptions options, string dbSource, string connectionStrings)
        {
            if (string.IsNullOrEmpty(connectionStrings))
            {
                throw new ArgumentException($"未配置[{dbSource}]链接字符串", "dbSource");
            }
            string microDbType = "mysql";
            if (connectionStrings.Contains("DbType="))
            {
                var dbTypeStr = connectionStrings.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(a => a.StartsWith("DbType="));
                connectionStrings = connectionStrings.Replace(";" + dbTypeStr, "");
                microDbType = dbTypeStr.Replace("DbType=", "").Trim();
            }
            options.DbSource = dbSource;
            options.MicroDbType = microDbType;
            options.DbConnectionString = connectionStrings;
        }
    }
}
